//
//  CCVSJBOLView.m
//  CollectionViewTest
//
//  Created by Pasirstein, David B on 4/30/13.
//  Copyright (c) 2013 Pasirstein, David B. All rights reserved.
//

#import "CCVSJBOLView.h"
#import "CCVSListOfStrings.h"
#import "CCVSCommon.h"

@interface CCVSJBOLView ()
@property (nonatomic,weak) UIViewController<CCVSCustomViewDelegate> * vc;
@property (nonatomic,weak) UIColor * textColor;
@property (nonatomic,weak) UIColor * bgColor;

@end

@implementation CCVSJBOLView

@synthesize data = _data;
@synthesize vc = _vc;
@synthesize textColor = _textColor;
@synthesize bgColor = _bgColor;


-(BOOL)isExpandable //will return if the view should support dyanamic resizing
{
    return YES;
}


//should return the frame size with width and height populated
+(CGSize)calcViewHeight:(CGFloat)viewWidth fromObject:(id<CCVSCustomDataType>)data
{
    BOOL maxRowsReached = NO;
    NSArray * frames = [CCVSJBOLView generateFrames:viewWidth
                                            fromObj:((CCVSListOfStrings*)data).strings
                                        shouldLimit:![data isExpanded]
                                    maxLimitReached:&maxRowsReached];
    CGRect rect = [(NSValue*)[frames lastObject] CGRectValue];
    CGFloat height = rect.origin.y + rect.size.height;
    if (maxRowsReached) {
        //we need to add room for the expand button
        height += [CCVSJBOLView calcSizeOfMoreOption:@CCVS_EXPANSION_TEXT].height;
    }
    return CGSizeMake(viewWidth, height);
}

+(CGSize)referenceRect
{
    return [@"A" sizeWithFont:[UIFont fontWithName:@CCVS_FONTNAME size:CCVS_FONTSIZE]
     constrainedToSize:CGSizeMake(9999, 9999)
         lineBreakMode:NSLineBreakByWordWrapping];
}

+(CGSize)calcSizeOfMoreOption:(NSString*)text
{
    CGSize size = [text sizeWithFont:[UIFont fontWithName:@CCVS_EXPANSION_FONTNAME
                                                     size:CCVS_EXPANSION_FONTSIZE]
                             constrainedToSize:CGSizeMake(9999, 9999)
                                 lineBreakMode:NSLineBreakByWordWrapping];
    return size;
}

+(NSArray*)generateFrames:(CGFloat)maxWidth
                  fromObj:(NSArray*)strings
              shouldLimit:(BOOL)limit
          maxLimitReached:(BOOL*)max
{
    *max = NO;
    CGSize referenceSize = [CCVSJBOLView referenceRect];
    referenceSize.height += CCVS_BOARDERSIZE;
    
    NSMutableArray * frames = [[NSMutableArray alloc] init];
    //Example, we need to store CGRects so we need to use NSValue
    //[array addObject:[NSValue valueWithCGRect:CGRectMake(0,0,10,10)]];
    //CGRect someRect = [[array objectAtIndex:0] CGRectValue];
    CGSize size = CGSizeMake(0, 0);
    for (int i = 0; i < [strings count] ; i++) {
        size = [(NSString*)strings[i] sizeWithFont:[UIFont fontWithName:@CCVS_FONTNAME size:CCVS_FONTSIZE]
                constrainedToSize:CGSizeMake(maxWidth, 9999)
                    lineBreakMode:NSLineBreakByWordWrapping];

        CGRect prevRect;
        if (i>0) {
            prevRect = [(NSValue*)frames[i-1] CGRectValue];
        } else {
            prevRect = CGRectMake(0, 0, 0, 0);
        }
        //
        NSValue * value;
        if (i ==  0) {
            // first row
            value = [NSValue valueWithCGRect:CGRectMake(0,
                                                        0,
                                                        size.width,
                                                        size.height)];
            
            
        } else if (prevRect.size.height > referenceSize.height) {
            // if the previous row has more lines of text than the reference height
            value = [NSValue valueWithCGRect:CGRectMake(0,
                                                        prevRect.origin.y + prevRect.size.height + CCVS_BOARDERSIZE,
                                                        size.width,
                                                        size.height)];
            
        } else if (maxWidth >= (size.width + prevRect.origin.x + prevRect.size.width + CCVS_BOARDERSIZE)) {
            //we have room to add the label on this row
            value = [NSValue valueWithCGRect:CGRectMake(prevRect.origin.x + prevRect.size.width + CCVS_BOARDERSIZE,
                                                        prevRect.origin.y,
                                                        size.width,
                                                        size.height)];
        } else {
            // we are out of room on this row so we must add to next row
            value = [NSValue valueWithCGRect:CGRectMake(0,
                                                        prevRect.origin.y + prevRect.size.height + CCVS_BOARDERSIZE,
                                                        size.width,
                                                        size.height)];
        }
        [frames addObject:value];
        CGRect rect = [value CGRectValue];
        if (limit &&
            ((rect.origin.y + rect.size.height)/referenceSize.height) > MAX_ROWS_BEFORE_EXPAND) {
            *max = YES;
            //did we go too far?
            [frames removeLastObject];
            break; //break out of the loop...
        }
        
        
    } //end for loop
    return frames;
}

//initialize the object...primary way it will be init'ed
-(id)initWithData:(id<CCVSCustomDataType>)data withFrame:(CGRect)frame viewController:(UIViewController*)vc
{
    self  = [super initWithFrame:frame];
    self.data = data;
    self.vc = (UIViewController<CCVSCustomViewDelegate> *)vc;
    self.bgColor = ((CCVSListOfStrings*)data).bgColor;
    self.textColor = ((CCVSListOfStrings*)data).textColor;
    return self;
}

//should build view to be displayed (would likely return self)
-(UIView*)buildView
{
    BOOL maxRowsReached = NO;
    NSArray * frames = [CCVSJBOLView generateFrames:self.frame.size.width
                                            fromObj:((CCVSListOfStrings*)self.data).strings
                                        shouldLimit:![self.data isExpanded]
                                    maxLimitReached:&maxRowsReached];
    for (int i = 0; i < [frames count]; i++) {
        UILabel * label = [self createLabelForView:((CCVSListOfStrings*)self.data).strings[i]
                                         withFrame:[(NSValue*)frames[i] CGRectValue]];
        [self addSubview:label];
    }
    if (maxRowsReached) {
        //we need to add the expansion label
        CGRect frame = [(NSValue*)[frames lastObject] CGRectValue];
        CGSize size = [CCVSJBOLView calcSizeOfMoreOption:@CCVS_EXPANSION_TEXT];
        UILabel * exp = [self createLabelForExpansion:@CCVS_EXPANSION_TEXT
                                            withFrame:CGRectMake(0,
                                                                 frame.origin.y + frame.size.height + CCVS_BOARDERSIZE,
                                                                 size.width,
                                                                 size.height)];
        [self addSubview:exp];
    }
    return self;
}

-(BOOL)willSegueOnEvent //true/false if the view will require a segue
{
    return NO;
}

//Creates the label...note if this is a hyperlink, the label is actually
//a CCSV Extended Label
-(UILabel*)createLabelForView:(id)data withFrame:(CGRect)frame
{
    UILabel * label1;
    NSString * text;
    //we have a regular label
    label1 = [[UILabel alloc] initWithFrame:frame];
    text = ((NSString*)data);
    label1.backgroundColor = (self.bgColor)? self.bgColor : [UIColor blueColor];
    label1.textColor = (self.textColor) ? self.textColor : [UIColor whiteColor];
    label1.numberOfLines = 0;
    label1.lineBreakMode = NSLineBreakByWordWrapping;
    label1.font = [UIFont fontWithName:@CCVS_FONTNAME size:CCVS_FONTSIZE];
    
    //add the data to the label
    label1.text = text;
    
    return label1;
}

//Creates the label...note if this is a hyperlink, the label is actually
//a CCSV Extended Label
-(UILabel*)createLabelForExpansion:(NSString*)data withFrame:(CGRect)frame
{

    UILabel * label1;
    NSString * text;
    //we have a regular label
    label1 = [[UILabel alloc] initWithFrame:frame];
    text = ((NSString*)data);
    label1.backgroundColor = [UIColor whiteColor];
    label1.textColor = [UIColor blackColor];
    label1.numberOfLines = 0;
    label1.lineBreakMode = NSLineBreakByWordWrapping;
    label1.font = [UIFont fontWithName:@CCVS_EXPANSION_FONTNAME size:CCVS_EXPANSION_FONTSIZE];
    
    //add the data to the label
    label1.text = text;

    label1.userInteractionEnabled = YES; //enable it for gestures
    //now add a gesture
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureForExpansion:)];
    tap.numberOfTapsRequired = 1;
    [label1 addGestureRecognizer:tap];
        
    return label1;
}

-(void)handleTapGestureForExpansion:(UITapGestureRecognizer *) gesture
{
    //proxy method for gesture to view controller with correct object
    [self.vc toggleExpantionAndRefreshView:self forDataType:self.data];
}



@end
